package com.wh.tokenizer;

import com.wh.exception.JsonParseException;

import java.io.IOException;
import java.io.Reader;

/**
 * 一个自动缓冲的 字符流
 *
 * @author wang hang
 */
public class CharReader {

    static final int BUFFER_SIZE = 1024;

    private Reader reader;

    private char[] buffer;

    private int pos;

    private int size;

    public CharReader(Reader reader) {
        this.reader = reader;
        buffer = new char[BUFFER_SIZE];
    }

    /**
     * 返回 pos 下标处的字符
     * @return
     */
    public char peek() throws IOException {
        if (pos == size) {
            fillBuffer("EOF");
        }
        return buffer[pos];
    }

    /**
     * 返回 pos 下标处的字符，并将 pos + 1，最后返回字符
     * @return
     * @throws IOException
     */
    public char next() throws IOException {
        if (pos == size) {
            fillBuffer("EOF");
        }

        return buffer[pos++];
    }

    public boolean hasMore() throws IOException {
        if (pos < size) {
            return true;
        }
        fillBuffer(null);
        return pos < size;
    }

    void fillBuffer(String message) throws IOException, JsonParseException {
        int n = reader.read(buffer);
        if (n == -1) {
            if (message != null) {
                throw new JsonParseException(message);
            }
            return;
        }
        pos = 0;
        size = n;
    }
}
